from socket import *

import struct
udpSocket = socket(AF_INET, SOCK_DGRAM)

ip = '192.168.131.58'
port = 69
addr = (ip, port)

filename = b'test.pdf'

# 读写请求的数据包
sendData = struct.pack("!H"+str(len(filename))+"sb5sb",1,filename,0,b"octet",0)
# 发送读写请求
udpSocket.sendto(sendData, addr)


while True:
    # 接收到服务返回回来的数据
    responseData = udpSocket.recvfrom(1024)

    recvData, recvAddr = responseData
    # print(recvData, recvAddr)

    # 拆包操作
    opcode, blockNum = struct.unpack("!HH", recvData[:4])
    # print(opcode, blockNum)

    if opcode == 3:
        if blockNum == 1:
            fid = open(filename, 'wb')
        
        # 拆数据
        dataFMT = "!" + str(len(recvData) - 4) + "s"
        # print(date_fmt)
        dataContent = struct.unpack(dataFMT, recvData[4:])
        # print(type(dataContent))
        # print(dataContent)
        fid.write(dataContent[0])

        # 发送ack
        ackData = struct.pack("!HH", 4, blockNum)
        udpSocket.sendto(ackData, recvAddr)

        #  若接收到数据长度小于512 + 2 + 2说明传输完成
        if len(recvData) < 516:
            print("dowload sucess")
            fid.close()
            break
    elif opcode == 5:
        print("something error")
        break


